package com.social.socialservice.controller;


import com.social.socialservice.dal.PostDAL;
import com.social.socialservice.dal.UserDAL;
import com.social.socialservice.model.PostInfo;
import com.social.socialservice.model.UserInfo;
import com.social.socialservice.unit.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 图片与视频文件上传
 */
@CrossOrigin
@RestController
public class FileUploadController {
    //图片存放的相对于项目的相对位置
    final static String PIC_PATH = "static/img/";
    //视频存放的位置
    final static String VID_PATH = "static/video/";
    //头像存放位置
    final static String Header_PATH = "static/person/header/";
    //背景存放位置
    final static String PersonBG_PATH = "static/person/bg/";
    final static String DEL_PATH = "src/main/resources/static/";

    @Autowired
    PostDAL postDAL;

    @Autowired
    UserDAL userDAL;

    /**************************************************
     * 封装文件上传，单文件，格式类型
     */
    public String uploadFile(MultipartFile file, HttpServletRequest request, String upload_url, String load_url) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + upload_url; // 存储路径

        File folder = new File(savePath + datePrefix); //生成带当前日期的文件路径

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

//        String randomName = multiRequest.getFile(file_tag).getOriginalFilename(); //获取图片名
        String randomName = file.getOriginalFilename();
        //生成随机数确保唯一性，并加上图片后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."), randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径
        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
//            multiRequest.getFile(file_tag).transferTo(fileToSave); //图片存储到服务端
            file.transferTo(fileToSave);//图片存储到服务端
            System.out.println("上传成功");
            String returnPath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + load_url + datePrefix + "/" + saveName;

            return returnPath;

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return "";
    }

    /**
     * 编辑用户个人资料
     * 背景图片/头像/其他信息等
     */
    @PostMapping("/EditPersonalInfo")
    public Response EditPersonalInfoByUploadFile(MultipartHttpServletRequest multiRequest, HttpServletRequest request) {

        //分别获取背景和头像列表
        List<MultipartFile> bgImgList = multiRequest.getFiles("user_bgimg");
        List<MultipartFile> headerImgList = multiRequest.getFiles("user_headimg");
        System.out.println("背景：" + bgImgList.size());
        System.out.println("头像：" + headerImgList.size());
        String user_bgimg = "";
        String user_headimg = "";
        for (MultipartFile file : bgImgList) {
            user_bgimg = uploadFile(file, request, PersonBG_PATH, "/person/bg/");
        }
        for (MultipartFile file : headerImgList) {
            user_headimg = uploadFile(file, request, Header_PATH, "/person/header/");
        }
        //装载表单数据
        UserInfo userInfo = new UserInfo();
        //上传了头像才添加头像字段
        if (user_headimg != "") {
            userInfo.setUser_headimg(user_headimg);
        }
        //上传了背景才添加背景字段
        if (user_bgimg != "") {
            userInfo.setUser_bgimg(user_bgimg);
        }
        userInfo.setUser_id(Integer.parseInt(request.getParameter("user_id")));
        userInfo.setUser_nickname(request.getParameter("user_nickname"));
        userInfo.setUser_info(request.getParameter("user_info"));
        //执行数据库修改操作，修改成功则返回编辑成功
//        System.out.println(userInfo);
        if (userDAL.EditUserInfo(userInfo)) {
            return new Response(200, "编辑成功", null);
        } else {
            //上传失败
            return new Response(203, "编辑失败", null);
        }
    }

    /**
     * 发帖上传图片和视频优化封装方法
     */
    public String uploadPostComponents(MultipartFile file, HttpServletRequest request,String upload_url, String load_url) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + upload_url; // 存储路径

        File folder = new File(savePath + datePrefix); //生成带当前日期的文件路径

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        String randomName = file.getOriginalFilename();
        //生成随机数确保唯一性，并加上图片后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."), randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径

        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
            file.transferTo(fileToSave);//图片存储到服务端
            String returnPath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + load_url + datePrefix + "/" + saveName;

            return returnPath;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * 发布帖子优化方法
     */
    @PostMapping("/addPostHandler")
    public Response addPostHandler(MultipartHttpServletRequest multiRequest, HttpServletRequest request){
        //分别获取图片和视频列表
        List<MultipartFile> uploadImgList = multiRequest.getFiles("image");
        List<MultipartFile> uploadVideoList = multiRequest.getFiles("video");
        //保存图片与视频地址字段
        String tp_url = "";
        String sp_url = "";
        //获取上传图片列表
        for (MultipartFile file : uploadImgList) {
            String url = uploadPostComponents(file, request,PIC_PATH,"/img/");
            tp_url += url + "|";
        }
        if(tp_url!=""){
            tp_url = tp_url.substring(0, tp_url.length() - 1);
        }
        //获取上传视频列表
        for (MultipartFile file : uploadVideoList) {
            String url = uploadPostComponents(file, request,VID_PATH,"/video/");
            sp_url = url;
        }

        //装载数据
        if(addPostForm(request, sp_url, tp_url)){
            return new Response(200,"发帖成功",null);
        }else{
            return new Response(203,"发帖成功",null);
        }
    }


    /**
     * 封装文件上传表单数据
     */
    private boolean addPostForm(HttpServletRequest request, String sp_url, String tp_url) {
        PostInfo postInfo = new PostInfo();
        postInfo.setUser_id(Integer.parseInt(request.getParameter("user_id")));
        postInfo.setZf_parent_id(Integer.parseInt(request.getParameter("zf_parent_id")));
        postInfo.setPl_parent_id(Integer.parseInt(request.getParameter("pl_parent_id")));
        postInfo.setZf_user_id(Integer.parseInt(request.getParameter("zf_user_id")));
        postInfo.setReply_user_id(Integer.parseInt(request.getParameter("reply_user_id")));
        postInfo.setReply_user_account(request.getParameter("reply_user_account"));
        postInfo.setPost_content(request.getParameter("post_content"));
        postInfo.setPost_replylimit(Integer.parseInt(request.getParameter("post_replylimit")));
        postInfo.setPost_ip(request.getParameter("post_ip"));
        postInfo.setPost_lan_ip(request.getParameter("post_lan_ip"));
        postInfo.setPost_location(request.getParameter("post_location"));
        postInfo.setPost_city(request.getParameter("post_city"));
        postInfo.setPost_country(request.getParameter("post_country"));
        postInfo.setPost_regionName(request.getParameter("post_regionName"));
        postInfo.setPost_lat(request.getParameter("post_lat"));
        postInfo.setPost_lon(request.getParameter("post_lon"));
        //如果图片字符串为空，则未上传图片
        if(tp_url!=""){
            postInfo.setTp_url(tp_url);
        }
        //如果视频字符串为空，则未上传视频
        if(sp_url!=""){
            postInfo.setSp_url(sp_url);
        }
        // 提交数据库保存
        return postDAL.addPost(postInfo);
    }



    /*******************************************************************************
     * 上面部分为优化后的方法
     */


    /**
     * 单文件
     * 图片文件上传请求接口
     */
    @PostMapping("/uploadpic")
    public Response uploadPic(MultipartHttpServletRequest multiRequest, HttpServletRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + PIC_PATH; // 存储路径

        File folder = new File(savePath + datePrefix); //生成带当前日期的文件路径

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        String randomName = multiRequest.getFile("image").getOriginalFilename(); //获取图片名

        //生成随机数确保唯一性，并加上图片后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."), randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径

        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
            multiRequest.getFile("image").transferTo(fileToSave); //图片存储到服务端
            String returnPath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + "/img/" + datePrefix + "/" + saveName;

            return new Response(200, "上传成功", returnPath);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response(401, "上传失败", "uploadPic错误");
    }

    /**
     * 单文件上传改造
     */
    public String uploadsingle(MultipartFile file, HttpServletRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + PIC_PATH; // 存储路径

        File folder = new File(savePath + datePrefix); //生成带当前日期的文件路径

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        //String randomName = multiRequest.getFile("image").getOriginalFilename(); //获取图片名
        String randomName = file.getOriginalFilename();
        //生成随机数确保唯一性，并加上图片后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."), randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径

        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
            //multiRequest.getFile("image").transferTo(fileToSave); //图片存储到服务端
            file.transferTo(fileToSave);//图片存储到服务端
            String returnPath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + "/img/" + datePrefix + "/" + saveName;

            return returnPath;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    /**
     * 多文件
     * 图片上传
     */
    @PostMapping("/uploadpics")
    public Response uploadPicMultipart(MultipartHttpServletRequest multiRequest, HttpServletRequest request) {
        try {
            List<String> list = new ArrayList<String>();
            String tp_url = "";
            List<MultipartFile> fileList = multiRequest.getFiles("image");
            for (MultipartFile file : fileList) {
                String url = uploadsingle(file, request);
                list.add(url);
                tp_url += url + "|";
            }
            tp_url = tp_url.substring(0, tp_url.length() - 1);
            //装载数据
            addForm(request, "", tp_url);
            if (list.size() > 0) {
                return new Response(200, "上传图片成功", list);
            } else {
                return new Response(203, "上传图片失败", null);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new Response(500, e.getMessage(), null);
        }

    }

    /**
     * 单视频文件上传
     */
    public String uploadVideoSingle(MultipartFile file, HttpServletRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //生成日期格式
        String datePrefix = dateFormat.format(new Date()); //生成当前日期作为前缀
        String savePath = "src/main/resources/" + VID_PATH; // 存储路径

        File folder = new File(savePath + datePrefix); //生成带当前日期的文件路径

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        String randomName = file.getOriginalFilename();
        //生成随机数确保唯一性，并加上视频后缀
        String saveName = UUID.randomUUID().toString() + randomName.substring(randomName.lastIndexOf("."), randomName.length());
        String absolutePath = folder.getAbsolutePath(); //转换成绝对路径

        try {
            File fileToSave = new File(absolutePath + File.separator + saveName);
            file.transferTo(fileToSave);//视频存储到服务端
            String returnPath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + "/video/" + datePrefix + "/" + saveName;

            return returnPath;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传视频失败";
    }

    /**
     * 多视频文件上传
     */
    @PostMapping("/uploadvideos")
    public Response uploadVideoMultipart(MultipartHttpServletRequest multiRequest, HttpServletRequest request) {

        try {


            //        List<String> list = new ArrayList<String>();
            String sp_url = "";
            List<MultipartFile> fileList = multiRequest.getFiles("video");
            for (MultipartFile file : fileList) {
                String url = uploadVideoSingle(file, request);
                sp_url = url;
            }
            //装载数据
            addForm(request, sp_url, "");
            if (sp_url != "") {
                return new Response(200, "上传视频成功", sp_url);
            } else {
                return new Response(203, "上传视频失败", sp_url);
            }
        } catch (Exception e) {
            return new Response(500, e.getMessage(), null);
        }
    }

    /**
     * 封装文件上传表单数据
     */
    private void addForm(HttpServletRequest request, String sp_url, String tp_url) {
        PostInfo postInfo = new PostInfo();
        postInfo.setUser_id(Integer.parseInt(request.getParameter("user_id")));
        postInfo.setZf_parent_id(Integer.parseInt(request.getParameter("zf_parent_id")));
        postInfo.setPl_parent_id(Integer.parseInt(request.getParameter("pl_parent_id")));
        postInfo.setReply_user_id(Integer.parseInt(request.getParameter("reply_user_id")));
        postInfo.setReply_user_account(request.getParameter("reply_user_account"));
        postInfo.setPost_content(request.getParameter("post_content"));
        postInfo.setPost_replylimit(Integer.parseInt(request.getParameter("post_replylimit")));
        postInfo.setPost_ip(request.getParameter("post_ip"));
        postInfo.setPost_lan_ip(request.getParameter("post_lan_ip"));
        postInfo.setPost_location(request.getParameter("post_location"));
        postInfo.setPost_city(request.getParameter("post_city"));
        postInfo.setPost_country(request.getParameter("post_country"));
        postInfo.setPost_regionName(request.getParameter("post_regionName"));
        postInfo.setPost_lat(request.getParameter("post_lat"));
        postInfo.setPost_lon(request.getParameter("post_lon"));
        //如果图片字符串为空，则未上传图片
        if(tp_url!=""){
            postInfo.setTp_url(tp_url);
        }
        //如果视频字符串为空，则未上传视频
        if(sp_url!=""){
            postInfo.setSp_url(sp_url);
        }
        // 提交数据库保存
        postDAL.addPost(postInfo);
    }


    /**
     * markdwon删除已经上传的图片后端api请求接口
     *
     * @param {删除图片的路径} imgurl
     */
    @RequestMapping(value = "/delImg", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response delImg(@RequestBody PostInfo postInfo) {
        //获取图片路径static里的路径地址
        String urlImg = postInfo.getTp_url().split("/", 4)[3];
        //服务器上多了个地址src/main/resources/static/studysys/img/2023-08-12/c90100d3-952f-443b-8a80-601cfe287f18.png
        //拼字符串去掉studysys/ urlImg.substring(9)
        String url = DEL_PATH + urlImg;
        //新建文件对象
        File fileDel = new File(url);
        if (!fileDel.exists()) {
            return new Response(404, "图片不存在" + url, postInfo.getTp_url());
        } else {
            fileDel.delete();
        }
        return new Response(200, "删除成功", postInfo.getTp_url());
    }


}
